import {createRouter, createWebHistory} from 'vue-router';
import HomeView from '../views/HomeView.vue';
import LoginView from '../views/LoginView.vue';
import RegisterView from '../views/RegisterView.vue';
import ChatView from '../views/ChatView.vue';
import UserProfileView from '../views/UserProfileView.vue'; // 导入用户管理页面
import authService from '../services/authService';

const router = createRouter({
    history: createWebHistory(process.env.BASE_URL),
    routes: [
        {
            path: '/',
            name: 'home',
            component: HomeView,
            meta: {
                requiresAuth: true
            }
        },
        {
            path: '/login',
            name: 'login',
            component: LoginView,
            meta: {
                requiresAuth: false
            }
        },
        {
            path: '/register',
            name: 'register',
            component: RegisterView,
            meta: {
                requiresAuth: false
            }
        },
        {
            path: '/chat/:character',
            name: 'chat',
            component: ChatView,
            meta: {
                requiresAuth: true
            }
        },
        // 添加用户管理页面路由
        {
            path: '/user/profile',
            name: 'userProfile',
            component: UserProfileView,
            meta: {
                requiresAuth: true
            }
        }
    ]
});

// 路由守卫，控制页面访问权限
router.beforeEach((to, from, next) => {
    const isAuthenticated = authService.isAuthenticated();

    // 如果需要登录但用户未登录，则重定向到登录页面
    if (to.meta.requiresAuth && !isAuthenticated) {
        next('/login');
    }
    // 如果用户已登录但尝试访问登录或注册页面，则重定向到首页
    else if (!to.meta.requiresAuth && isAuthenticated && (to.path === '/login' || to.path === '/register')) {
        next('/');
    }
    // 其他情况，正常访问
    else {
        next();
    }
});

export default router;